package com.cehome.cloudbox.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.cehome.cloudbox.constans.ExtensionTaskProperties;
import com.cehome.cloudbox.service.IProcCommonService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableMultiInstanceActivityEvent;
import org.flowable.engine.delegate.event.impl.FlowableMultiInstanceActivityEventImpl;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 全局的多实例任务启动监听
 * @author zfl
 */
@Component
@Slf4j
public class GlobalMultiInsActStartedListener extends AbstractFlowableEngineEventListener {

    @Resource
    protected RepositoryService repositoryService;
    @Resource
    private IProcCommonService iProcCommonService;

    @Override
    protected void multiInstanceActivityStarted(FlowableMultiInstanceActivityEvent event) {
        log.info("多实例任务启动监听开始");
        FlowableMultiInstanceActivityEventImpl eventImpl = (FlowableMultiInstanceActivityEventImpl) event;
        // 获取节点信息
        BpmnModel bpmnModel = repositoryService.getBpmnModel(eventImpl.getProcessDefinitionId());
        FlowElement flowElement = bpmnModel.getFlowElement(eventImpl.getActivityId());

        // 获取候选人数据
        String taskCandidateData = flowElement.getAttributeValue(
                ExtensionTaskProperties.NAMESPACE_URI, ExtensionTaskProperties.TASK_CANDIDATE_DATA);

        // 获取申请人
        String applyUserId = Convert.toStr(eventImpl.getExecution().getVariable(ExtensionTaskProperties.FLOWABLE_APPLY_USER_ID));

        // 获取候选人IDList
        List<String> userIdList = iProcCommonService.getUserIdList(taskCandidateData, applyUserId);
        log.info("会签人用户ID：{}", userIdList);
        // 设置会签环境变量
        if (ObjectUtil.isNotEmpty(userIdList)) {
            eventImpl.getExecution().setVariable(ExtensionTaskProperties.FLOWABLE_COUNTER_SIGNER_LIST, userIdList);
            // TODO 发送消息
        }

        log.info("多实例任务启动监听结束");
    }

}
